//
//  PhoneBook.m
//  Demo0015
//
//  Created by zTercel on 13-1-14.
//  Copyright (c) 2013年 zTercel. All rights reserved.
//

#import "PhoneBook.h"

@implementation PhoneBook
{
    NSMutableArray*     phoneBook;
}

-(id) init
{
    self = [super init];
    if (self)
    {
        phoneBook = [NSMutableArray arrayWithCapacity:100];
    }
    
    return self;
}

-(id) initWithPhone: (PhoneItem*)item
{
    self = [self init];
    if (self)
    {
        [self addPhone:item];
    }
    
    return self;
}

-(void) addPhone: (PhoneItem*)item
{
    [phoneBook addObject:item];
}

-(void) removePhone: (NSString*)name
{
    for (int ii = [phoneBook count] - 1; ii >= 0; ii--)
    {
        PhoneItem* item = [phoneBook objectAtIndex:ii];
        if (NSOrderedSame == [name compare:[item name] options:NSCaseInsensitiveSearch])
        {
            [phoneBook removeObject:item];
        }
    }
    
    return;
}

-(void) queryPhone: (NSString*)name
{
    NSUInteger queryCount     = 0;
    
    NSMutableString* prompt     = [NSMutableString string];
    NSMutableString* content    = [NSMutableString stringWithFormat:@"\n%-10s %-20s %-20s\n", "id", "name", "number"];
    [content appendString:@"=======================================================\n"];

    for (PhoneItem* item in phoneBook)
    {
        if (NSOrderedSame == [name compare:[item name] options:NSCaseInsensitiveSearch])
        {
            [content appendFormat:@"%-10lu %-20s %-20s\n", ++queryCount, [[item name] UTF8String], [[item number] UTF8String]];
        }
    }
    
    [prompt appendFormat: @"\nquery record count: %lu", queryCount];
    if (0 < queryCount)
    {
        [prompt appendString: content];
    }
    NSLog(@"%@", prompt);
    
}

-(void) sort
{
    [phoneBook sortUsingComparator:
      ^(id obj1, id obj2) {
          return [[obj1 name] compare:[obj2 name] options:NSCaseInsensitiveSearch];
      }];
    
    
    return;
}

-(NSUInteger) count
{
    return [phoneBook count];
}

-(void) description
{
    NSMutableString* content = [NSMutableString stringWithFormat:@"\nPhoneBook content:\n%-20s %-20s\n", "name", "number"];
    [content appendString:@"=======================================================\n"];
    for (PhoneItem* item in phoneBook)
    {
        [content appendFormat:@"%-20s %-20s\n", [[item name] UTF8String], [[item number] UTF8String]];
    }
    NSLog(@"%@", content);
    
    return;
}

@end
